<template>
  <view class="transfer-container">
    <uni-section title="设备信息" type="line"></uni-section>

    <!-- 设备基本信息展示 -->
    <view class="device-info-card">
      <view class="info-item">
        <text class="info-label">设备名称：</text>
        <text class="info-value">{{ deviceInfo.equipmentName || deviceInfo.name || '未知' }}</text>
      </view>
      <view class="info-item">
        <text class="info-label">设备编号：</text>
        <text class="info-value">{{ deviceInfo.equipmentCode || deviceInfo.code || '未知' }}</text>
      </view>
      <view class="info-item">
        <text class="info-label">设备型号：</text>
        <text class="info-value">{{ deviceInfo.model || '未知' }}</text>
      </view>
      <!-- <view class="info-item">
        <text class="info-label">设备状态：</text>
        <text class="info-value status" :class="statusClass">{{ statusText }}</text>
      </view> -->
    </view>

    <uni-section title="调拨记录" type="line"></uni-section>

    <view class="form-container">
      <uni-forms ref="form" :model="formData" :rules="rules" label-width="180rpx">
        <!-- 调拨类型 -->
        <!-- <uni-forms-item label="调拨类型" name="transferType" required>
          <uni-data-select v-model="formData.transferType" :localdata="transferTypeOptions" placeholder="请选择调拨类型" />
        </uni-forms-item> -->

        <!-- 调拨原因 -->
        <!-- <uni-forms-item label="调拨原因" name="transferReason" required>
          <uni-easyinput v-model="formData.transferReason" type="textarea" placeholder="请详细描述调拨原因" :autoHeight="true"
            :maxlength="500" />
        </uni-forms-item> -->

        <!-- 原位置 -->
        <uni-forms-item label="调出地点" name="transferOutLocation" required>
          <uni-easyinput v-model="formData.transferOutLocation" placeholder="请输入调出地点" :clearable="true" />
        </uni-forms-item>

        <!-- 目标位置 -->
        <uni-forms-item label="调入地点" name="transferInLocation" required>
          <uni-easyinput v-model="formData.transferInLocation" placeholder="请输入调入地点" :clearable="true" />
        </uni-forms-item>

        <!-- 调拨人员 -->
        <!--  <uni-forms-item label="调拨人员" name="transferPerson" required>
          <uni-easyinput v-model="formData.transferPerson" placeholder="请输入调拨人员姓名" :clearable="true" />
        </uni-forms-item> -->

        <!-- 调拨时间 -->
        <!-- <uni-forms-item label="调拨时间" name="transferTime" required>
          <uni-datetime-picker v-model="formData.transferTime" value-format="yyyy-MM-dd HH:mm:ss" type="datetime"
            placeholder="请选择调拨时间" />
        </uni-forms-item> -->

        <!-- 预计完成时间 -->
        <!--   <uni-forms-item label="预计完成时间" name="expectedCompletionTime" required>
          <uni-datetime-picker v-model="formData.expectedCompletionTime" value-format="yyyy-MM-dd HH:mm:ss" type="date"
            placeholder="请选择预计完成时间" />
        </uni-forms-item> -->

        <!-- 调拨状态 -->
        <!-- <uni-forms-item label="调拨状态" name="transferStatus" required>
          <uni-data-checkbox v-model="formData.transferStatus" :localdata="transferStatusOptions" />
        </uni-forms-item> -->

        <!-- 调拨备注 -->
        <uni-forms-item label="备注" name="remark">
          <uni-easyinput v-model="formData.remark" type="textarea" placeholder="请输入其他备注信息" :autoHeight="true"
            :maxlength="200" />
        </uni-forms-item>
      </uni-forms>
    </view>

    <!-- 操作按钮 -->
    <view class="action-buttons">
      <button class="action-btn cancel" @click="handleCancel">取消</button>
      <button class="action-btn submit" @click="handleSubmit">提交</button>
    </view>
  </view>
</template>

<script>
import { getEquipment, addTransferRecord } from '@/api/equipment/main'

export default {
  data() {
    return {
      equipmentId: null,
      deviceInfo: {},
      formData: {
        equipmentId: '',
        transferType: '',
        transferReason: '',
        transferOutLocation: '',
        transferInLocation: '',
        transferPerson: '',
        transferTime: '',
        expectedCompletionTime: '',
        transferStatus: '',
        remark: ''
      },
      rules: {
        transferType: {
          rules: [
            { required: true, errorMessage: '请选择调拨类型' }
          ]
        },
        transferReason: {
          rules: [
            { required: true, errorMessage: '请输入调拨原因' },
            { minLength: 5, maxLength: 500, errorMessage: '调拨原因长度为5-500个字符' }
          ]
        },
        transferOutLocation: {
          rules: [
            { required: true, errorMessage: '请输入调出地点' },
            { minLength: 1, maxLength: 100, errorMessage: '原位置长度为1-100个字符' }
          ]
        },
        transferInLocation: {
          rules: [
            { required: true, errorMessage: '请输入调入地点' },
            { minLength: 1, maxLength: 100, errorMessage: '目标位置长度为1-100个字符' }
          ]
        },
        transferPerson: {
          rules: [
            { required: true, errorMessage: '请输入调拨人员' },
            { minLength: 2, maxLength: 20, errorMessage: '调拨人员姓名长度为2-20个字符' }
          ]
        },
        transferTime: {
          rules: [
            { required: true, errorMessage: '请选择调拨时间' }
          ]
        },
        expectedCompletionTime: {
          rules: [
            { required: true, errorMessage: '请选择预计完成时间' }
          ]
        },
        transferStatus: {
          rules: [
            { required: true, errorMessage: '请选择调拨状态' }
          ]
        }
      },
      transferTypeOptions: [
        { text: '部门内调拨', value: '1' },
        { text: '跨部门调拨', value: '2' },
        { text: '项目调拨', value: '3' },
        { text: '维修调拨', value: '4' },
        { text: '临时调拨', value: '5' }
      ],
      transferStatusOptions: [
        { text: '待调拨', value: '1' },
        { text: '调拨中', value: '2' },
        { text: '已完成', value: '3' },
        { text: '已取消', value: '4' }
      ]
    }
  },
  computed: {
    // 状态文本
    statusText() {
      const statusMap = {
        1: '在线',
        2: '离线',
        3: '告警',
        4: '待报废',
        5: '维修中',
        6: '已报废'
      }
      return statusMap[this.deviceInfo.status] || statusMap[String(this.deviceInfo.status)] || '未知'
    },
    // 状态样式类
    statusClass() {
      const classMap = {
        1: 'status-online',
        2: 'status-offline',
        3: 'status-alarm',
        4: 'status-pending',
        5: 'status-repairing',
        6: 'status-scrapped'
      }
      return classMap[this.deviceInfo.status] || classMap[String(this.deviceInfo.status)] || 'status-unknown'
    }
  },
  async onLoad(options) {
    if (options.id) {
      this.equipmentId = options.id
      this.formData.equipmentId = options.id
      await this.fetchDeviceInfo()
    } else {
      uni.showToast({
        title: '缺少设备ID',
        icon: 'none'
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    }
  },
  methods: {
    // 获取设备信息
    async fetchDeviceInfo() {
      try {
        uni.showLoading({
          title: '加载中...'
        })
        const res = await getEquipment(this.equipmentId)
        const data = res && res.data ? res.data : res

        this.deviceInfo = data

        // 设置原位置为设备当前位置
        if (data.location) {
          this.formData.transferOutLocation = data.location
        }

        uni.hideLoading()
      } catch (error) {
        uni.hideLoading()
        console.error('获取设备信息失败:', error)
        uni.showToast({
          title: '获取设备信息失败',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      }
    },

    // 取消操作
    handleCancel() {
      uni.showModal({
        title: '确认取消',
        content: '确定要取消添加调拨记录吗？未保存的数据将丢失。',
        success: (res) => {
          if (res.confirm) {
            uni.navigateBack()
          }
        }
      })
    },

    // 提交表单
    handleSubmit() {
      this.$refs.form.validate().then(async (valid) => {
        if (valid) {
          try {
            uni.showLoading({
              title: '提交中...'
            })

            // 处理日期格式，将日期转换为 yyyy-MM-dd HH:mm:ss 格式
            const submitData = { ...this.formData }
            if (submitData.expectedCompletionTime) {
              // 如果日期格式是 yyyy-MM-dd，则添加 00:00:00
              if (submitData.expectedCompletionTime.match(/^\d{4}-\d{2}-\d{2}$/)) {
                submitData.expectedCompletionTime = submitData.expectedCompletionTime + ' 00:00:00'
              }
            }

            // 调用添加调拨记录的API
            const res = await addTransferRecord(submitData)

            uni.hideLoading()
            uni.showToast({
              title: '调拨记录添加成功',
              icon: 'success'
            })

            // 延迟返回上一页
            setTimeout(() => {
              // 标记上一页需要刷新
              try { uni.setStorageSync('refresh_equipment_list', Date.now()) } catch (e) { }
              uni.navigateBack()
            }, 1500)

          } catch (error) {
            uni.hideLoading()
            console.error('添加调拨记录失败:', error)
            uni.showToast({
              title: '添加调拨记录失败',
              icon: 'none'
            })
          }
        }
      }).catch((errors) => {
        console.log('表单验证失败:', errors)
        uni.showToast({
          title: '请检查输入信息',
          icon: 'none'
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.transfer-container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.device-info-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.info-label {
  font-size: 28rpx;
  color: #666;
  width: 160rpx;
  flex-shrink: 0;
}

.info-value {
  font-size: 28rpx;
  color: #333;
  flex: 1;

  &.status {
    padding: 6rpx 16rpx;
    border-radius: 20rpx;
    font-weight: 500;

    &.status-online {
      color: #34C759;
      background-color: #E8F5E8;
    }

    &.status-offline {
      color: #8E8E93;
      background-color: #F0F0F0;
    }

    &.status-alarm {
      color: #FF3B30;
      background-color: #FFE8E8;
    }

    &.status-pending {
      color: #FF9500;
      background-color: #FFF4E6;
    }

    &.status-repairing {
      color: #FF2D92;
      background-color: #FFE8F5;
    }

    &.status-scrapped {
      color: #5856D6;
      background-color: #E8E8FF;
    }

    &.status-unknown {
      color: #8E8E93;
      background-color: #F0F0F0;
    }
  }
}

.form-container {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
}

.action-buttons {
  display: flex;
  gap: 20rpx;
  padding: 20rpx;
  background: #fff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
}

.action-btn {
  flex: 1;
  height: 80rpx;
  border-radius: 12rpx;
  font-size: 28rpx;
  font-weight: 500;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-btn.cancel {
  background: #f0f0f0;
  color: #666;
}

.action-btn.submit {
  background: #007AFF;
  color: #fff;
}

.action-btn:active {
  opacity: 0.8;
}

// 表单项样式调整
.form-container :deep(.uni-forms-item) {
  margin-bottom: 8px !important;
  padding-bottom: 8px !important;
}

.form-container :deep(.uni-forms-item--border) {
  padding: 4px 0 !important;
}

.form-container :deep(.uni-forms-item__error) {
  padding-top: 2px !important;
}

:deep(.uni-forms-item__label) {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

:deep(.uni-easyinput__content) {
  border-radius: 12rpx;
  border: 1rpx solid #eee;
  background: #f9f9f9;
}

:deep(.uni-easyinput__content.is-focus) {
  border-color: #007AFF;
  background: #fff;
}

:deep(.uni-data-select) {
  border-radius: 12rpx;
  border: 1rpx solid #eee;
  background: #f9f9f9;
}

:deep(.uni-data-select.is-focus) {
  border-color: #007AFF;
  background: #fff;
}
</style>
